package com.estore.service;

import com.estore.model.Product;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 商品服务类，负责商品相关的业务逻辑
 */
public class ProductService {

    // 使用Map存储商品数据，key是商品ID，value是商品对象
    private final Map<String, Product> productData = new HashMap<>();
    private static String dataFilePath="products.dat";

    public ProductService() {
        loadConfig();
        loadData();

        if (productData.isEmpty()) {
            System.out.println("未找到数据文件，使用默认商品数据...");
            initializeDefaultData();
        }
    }

    private void loadConfig() {
        Properties props = new Properties();
        File configFile = new File("config.properties");

        if (!configFile.exists()) {
            System.out.println("配置文件不存在，使用默认路径: products.dat");
            dataFilePath = "products.dat";
            return;
        }

        try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile), "UTF-8")) {
            props.load(reader);
            dataFilePath = props.getProperty("data.file.path", "products.dat");
            System.out.println("配置文件加载成功，数据文件路径: " + dataFilePath);
        } catch (IOException e) {
            System.out.println("加载配置文件失败: " + e.getMessage() + "，使用默认路径");
            dataFilePath = "products.dat";
        }
    }

    private void initializeDefaultData() {
        // 为Java从入门到精通添加标签
        Set<String> javaTags = new HashSet<>();
        javaTags.add("编程");
        javaTags.add("畅销");
        javaTags.add("热门");
        productData.put("001", new Product("001", "Java从入门到精通", 99.0, 100, javaTags));

        // 为高性能MySQL添加标签
        Set<String> mysqlTags = new HashSet<>();
        mysqlTags.add("数据库");
        mysqlTags.add("技术");
        mysqlTags.add("畅销");
        productData.put("002", new Product("002", "高性能MySQL", 128.5, 50, mysqlTags));

        //为颈椎康复指南添加标签
        Set<String> recoverTags = new HashSet<>();
        recoverTags.add("健康");
        recoverTags.add("养生");
        recoverTags.add("畅销");
        productData.put("003", new Product("003", "颈椎康复指南", 45.0, 200, recoverTags));

        //为生发秘籍添加标签
        Set<String> hairTags = new HashSet<>();
        hairTags.add("养生");
        hairTags.add("爆款");
        hairTags.add("新品");
        productData.put("004", new Product("004", "生发秘籍", 88.0, 0, hairTags));

        // 为重生之我成为了黑帮大佬添加标签
        Set<String> novelTags = new HashSet<>();
        novelTags.add("小说");
        novelTags.add("热门");
        novelTags.add("娱乐");
        productData.put("005", new Product("005", "重生之我成为了黑帮大佬", 58.0, 80, novelTags));

        //为美味家常菜~新手小白的入门秘籍添加标签
        Set<String> dishTags = new HashSet<>();
        dishTags.add("烹饪");
        dishTags.add("热门");
        dishTags.add("新品");
        productData.put("006", new Product("006", "美味家常菜~新手小白的入门秘籍", 110.0, 20,dishTags));

        //为语言的艺术添加标签
        Set<String> artTags = new HashSet<>();
        artTags.add("艺术");
        artTags.add("社交");
        artTags.add("新品");
        productData.put("007", new Product("007", "语言的艺术", 19.9, 1000,artTags));

        saveData(); // 保存默认数据
    }

    /**
     * 获取所有商品列表
     */
    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    /**
     * 根据ID查找商品
     */
    public Product findProductById(String id) {
        return productData.get(id);
    }

    /**
     * 添加新商品
     */
    public boolean addProduct(Product product) {
        if (productData.containsKey(product.getId())) {
            return false; // 商品ID已存在
        }
        productData.put(product.getId(), product);
        saveData();
        return true;
    }

    /**
     * 更新商品信息
     */
    public boolean updateProduct(Product product) {
        if (!productData.containsKey(product.getId())) {
            return false; // 商品不存在
        }
        productData.put(product.getId(), product);
        saveData();
        return true;
    }

    /**
     * 删除商品
     */
    public boolean deleteProduct(String productId) {
        if (!productData.containsKey(productId)) {
            return false; // 商品不存在
        }
        productData.remove(productId);
        saveData();
        return true;
    }

    /**
     * 调整商品库存
     */
    public boolean adjustStock(String productId, int quantity) {
        Product product = productData.get(productId);
        if (product == null) {
            return false; // 商品不存在
        }
        int newStock = product.getStock() + quantity;
        if (newStock < 0) {
            return false; // 库存不足
        }
        product.setStock(newStock);
        saveData();
        return true;
    }

    /**
     * 购买商品（减少库存）
     */
    public boolean purchaseProduct(String productId, int quantity) {
        return adjustStock(productId, -quantity);
    }

    /**
     * 获取商品标签
     */
    public Set<String> getProductTags(String productId) {
        Product product = productData.get(productId);
        return product != null ? product.getTags() : new HashSet<>();
    }

    /**
     * 为商品添加标签
     */
    public boolean addTagToProduct(String productId, String tag) {
        Product product = productData.get(productId);
        if (product == null) {
            return false;
        }
        product.getTags().add(tag);
        saveData();
        return true;
    }

    /**
     * 从商品移除标签
     */
    public boolean removeTagFromProduct(String productId, String tag) {
        Product product = productData.get(productId);
        if (product == null) {
            return false;
        }
        product.getTags().remove(tag);
        saveData();
        return true;
    }

    /**
     * 保存数据到文件
     */
    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
            oos.writeObject(productData);
            System.out.println("商品数据已保存到: " + dataFilePath);
        } catch (IOException e) {
            System.out.println("保存数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 从文件加载数据
     */
    @SuppressWarnings("unchecked")
    public void loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) {
            System.out.println("数据文件不存在: " + dataFilePath);
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            Map<String, Product> loadedData = (Map<String, Product>) ois.readObject();
            productData.clear();
            productData.putAll(loadedData);
            System.out.println("商品数据已从文件加载: " + dataFilePath + "，共加载 " + loadedData.size() + " 个商品");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 备份数据文件
     */
    public void backupData() throws IOException {
        File sourceFile = new File(dataFilePath);
        if (!sourceFile.exists()) {
            throw new IOException("源数据文件不存在: " + dataFilePath);
        }

        String backupFilePath = dataFilePath + ".bak";
        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(backupFilePath)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }

        System.out.println("数据已备份到: " + backupFilePath);
    }
}